Noah said:
I don't know of a single compiler that would allow you to do this
without warning; I think they're required to. Most compilers have a
switch that allows you to make warnings an error.
The code:
double somefunc()
{
double value= 1.0;
// Perform some operations
return value;
}
int main()
{
int x= somefunc();
}
john@ubuntu:~/Projects/anjuta/cpp/src$ g++ -ansi -pedantic-errors -Wall main.cc -o foobar
main.cc: In function ‘int main()’:
main.cc:14: warning: unused variable ‘x’
john@ubuntu:~/Projects/anjuta/cpp/src$
So now you know one compiler that allows this without a warning.
john@ubuntu:~/Projects/anjuta/cpp/src$ g++ -v
Using built-in specs.
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.3.2-1ubuntu12'
--with-bugurl=file:///usr/share/doc/gcc-4.3/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++
--prefix=/usr --enable-shared --with-system-zlib --libexecdir=/usr/lib --without-included-gettext
--enable-threads=posix --enable-nls --with-gxx-include-dir=/usr/include/c++/4.3 --program-suffix=-4.3
--enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --enable-mpfr --enable-checking=release
--build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.3.2 (Ubuntu 4.3.2-1ubuntu12)
john@ubuntu:~/Projects/anjuta/cpp/src$
I think, perhaps,
that this is more what you want to illustrate:
int somefunc();
int main()
{
only double x = somefunc(); // error
}
I just don't see why that would help you. Furthermore, I'd very much
recommend against anything like this:
only int somefunc();
It's the caller's responsibility what to do with the information
returned by "somefunc", including to totally ignore it. Something like
this has a bit of a smell to it.
If the programmer wants not having type safety on the returned type, he can define the function without the
keyword only, in the following style:
double somefunc()
{
only double value= 1.0;
// Perform some operations
return value;
}
int main()
{
int i= somefunc(); //OK
double d= somefunc(); //OK
only double od= somefunc(); // OK
}
So noone forces the programer to define the function returning "only double". In other words, the feature does
not get in the way of the programmer if he wishes not using it.
Normally you have preconditions that
must be met before the function can be called, and postconditions that
must be supplied by the function. I've never heard of imposing
post-conditions that must be met by the client, yet that's what you seem
to be proposing by putting only in the declaration of the function.
If you do not want to use this type-safe ability of returning a value, you may not use it, while you may use
other abilities of "only", if you want.