Compile error despite override - c++

Sorry if this is such an easy question, there must be something I don't understand about inheritance, virtual and override in c++. In the following example, I get a compile-time error relative to a virtual method that I specifically override to avoid such error in a child class. Am I doing something wrong?
#include <array>
#include <deque>
template <class T, class C>
struct foo
{
virtual const C& data() const =0;
inline virtual T& operator[] ( unsigned n ) const
{ return const_cast<T&>( data()[n] ); }
};
/**
* The implementation of foo::operator[] is useful for classes inheriting
* with simple sequence containers like:
* foo<T,std::deque<T>>, foo<T,std::vector<T>>, ..
*
* But the following requires operator[] to be redefined:
*/
template <class T, unsigned N>
struct baz
: public foo<T, std::deque<std::array<T,N>> >
{
typedef std::deque<std::array<T,N>> data_type;
data_type m_data;
inline const data_type& data() const
{ return m_data; }
inline virtual T& operator[] ( unsigned n ) const override
{ return const_cast<T&>( data()[n/N][n%N] ); }
};
int main()
{
baz<double,3> b; // throws an error relative to foo::operator[] depsite override
}
EDIT 1 The error:
clang++ -std=c++0x -Wall virtual_operator.cpp -o virtual_operator.o
virtual_operator.cpp:11:12: error: const_cast from 'const value_type' (aka 'const std::__1::array<double, 3>') to 'double &' is not allowed
{ return const_cast<T&>( data()[n] ); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~
virtual_operator.cpp:26:8: note: in instantiation of member function 'foo<double, std::__1::deque<std::__1::array<double, 3>, std::__1::allocator<std::__1::array<double, 3> > > >::operator[]'
requested here
struct baz
^
1 error generated.
EDIT 2 I consider this to be part of the question; if compiling fails because foo::operator[] is still callable in baz, then why does it compile fine if I don't declare foo::operator[] as virtual (ie, hiding instead of overriding)?

The issue is that although you are only intending to call the derived operator[] function on baz instances, the compiler still needs to generate code for the base class because that function is still callable on baz instances. In this case, generating that code results in a type error, because you are trying to cast a const std::array<double,3> into a double&.
In order to fix this, you should have different parts of the hierarchy which define an operator which will work for all its children, like so (with non-pertainent stuff removed):
template <class T, class C>
struct foo
{
inline virtual T& operator[] ( unsigned n ) const = 0;
};
template <class T>
struct bar
: public foo<T,std::deque<T>>
{
inline virtual T& operator[] ( unsigned n ) const override
{ return const_cast<T&>( data()[n] ); }
};
template <class T, unsigned N>
struct baz
: public foo<T, std::deque<std::array<T,N>> >
{
inline virtual T& operator[] ( unsigned n ) const override
{ return const_cast<T&>( data()[n/N][n%N] ); }
};
This way if you have any other versions you want to add later, you can derive from bar or baz and not need to define the operator per-child.

Related

C++ template generalization for const type

I am doing a small research here, which requires at some stage, that I have different classes doing (or not doing) operation on some data, depending on its constness.
A small example is like this (http://coliru.stacked-crooked.com/a/75c29cddbe6d8ef6)
#include <iostream>
template <class T>
class funny
{
public:
funny(T& a) : v(a) {v -= 1; }
virtual ~funny() { v += 1; }
operator T() {return v;}
private:
T& v;
};
#define V(a) funny<decltype(a)>(a)
int main()
{
char t[] = "ABC"; // <-- HERE
if( V( t[0] ) == (char)'A')
{
std::cout << "Pass" << t[0];
}
else
{
std::cout << "No Pass" << t[0];
}
}
Now, comes the question:
if I modify the line marked <-- HERE to be
const char t[] = "ABC";
I get the following compilation error:
main.cpp: In instantiation of 'funny<T>::funny(T&) [with T = const char&]':
main.cpp:21:7: required from here
main.cpp:7:28: error: assignment of read-only location '((funny<const char&>*)this)->funny<const char&>::v'
funny(T& a) : v(a) {v -= 1; }
~~^~~~
main.cpp: In instantiation of 'funny<T>::~funny() [with T = const char&]':
main.cpp:21:7: required from here
main.cpp:8:27: error: assignment of read-only location '((funny<const char&>*)this)->funny<const char&>::v'
virtual ~funny() { v += 1; }
~~^~~~
Which is totally understandable, since I try to modify a constant. Compiler is right here. However, I really need this to work also for const data, so I tried to create a const specialization of the template:
template <class T>
class funny <T const>
{
public:
funny(const T& a) : v(a) {}
operator T() {return v;}
private:
const T& v;
};
But regardless, the compiler does not find it, and still tries to compile the non-const version.
Any ideas on how to make this happen?
decltype(t[0]) deduces to const char&, which doesn't match your const char specialization. You have two options:
1) Change your specialization to template <class T> class funny <T const&>. That will work for this case, but won't work for const int FOO = 42; V(FOO);.
2) Change your V macro to always deduce to a non-reference type:
#define V(a) funny<typename std::remove_reference<decltype(a)>::type>(a)
Compiles if you change:
template <class T>
class funny <T const>
to:
template <class T>
class funny <const T&>

Cannot instantiate abstract class: Why is the template parameter (reference) causing this?

I am having trouble with some code.
'Bar' : cannot instantiate abstract class
I have (finally) been able to recreate the error in a small amount of code.
struct SomeStruct
{
// ******
};
template <typename TIN, typename TOUT, typename TINDEX>
struct IFoo
{
public:
virtual void add(const TIN item) = 0; // <-- BAD
//virtual void add(const TOUT& item) = 0; // <-- GOOD
// ******
};
template <typename TVALUE, typename TINDEX>
struct Bar : IFoo<TVALUE &, TVALUE, TINDEX>
{
public:
void add(const TVALUE& item)
{
// ******
}
// ******
};
int main(int argc, char *argv[])
{
SomeStruct someStruct;
Bar<SomeStruct, int> bar = Bar<SomeStruct, int>();
bar.add(someStruct);
// ******
}
Can anyone please advise WHY using a reference with the template parameter is causing this?
The issue here is that when you write const TIN and TIN is a reference type, the const applies to the reference and not to the value type.
This is why you are seeing different behaviour for const TIN and const TOUT& even when you think they should be the same.
A simple fix for this is to add the const to the value type in your IFoo instantiation:
struct Bar : IFoo<const TVALUE &, TVALUE, TINDEX>
// here ^^^^
Your problem goes back to basic concepts like function signature: a function signature/prototype is given by the function name, the number of parameters, datatype of parameters and the order of appearance of those parameters.
For any two functions if any of the above differ, than you are dealing with two different functions.
More exactly, these two represent two different signatures:
virtual void add(const TIN item) = 0;
virtual void add(const TOUT& item) = 0;
Since you implement only the second one in the derived class, you get the error.
We can simply your example further to:
template <typename T>
struct IFoo {
virtual void add(const T item) = 0;
};
template <typename T>
struct Bar : IFoo<T&> {
void add(const T& item) { }
};
In Bar, you are taking item as a reference to const T. In IFoo, you are declaring a pure virtual method that takes a const reference to T. But all references are inherently const, so that's redundant - it's equivalent to just taking a reference to T.
For Bar<int> - the signature of IFoo::add() is void add(int& ) whereas Bar::add() is void add(const int& ). Those signatures don't match - hence Bar is still an abstract class. Just one that hid IFoo::add().
If you have a C++11 compiler, you should prefer to add the override keyword to Bar::add() so that you would get a compiler error for:
main.cpp:15:10: error: 'void Bar<T>::add(const T&) [with T = int]' marked 'override', but does not override
void add(const T& ) override { }
^

How do I avoid implicit conversions on non-constructing functions?

How do I avoid implicit casting on non-constructing functions?
I have a function that takes an integer as a parameter,
but that function will also take characters, bools, and longs.
I believe it does this by implicitly casting them.
How can I avoid this so that the function only accepts parameters of a matching type, and will refuse to compile otherwise?
There is a keyword "explicit" but it does not work on non-constructing functions. :\
what do I do?
The following program compiles, although I'd like it not to:
#include <cstdlib>
//the function signature requires an int
void function(int i);
int main(){
int i{5};
function(i); //<- this is acceptable
char c{'a'};
function(c); //<- I would NOT like this to compile
return EXIT_SUCCESS;
}
void function(int i){return;}
*please be sure to point out any misuse of terminology and assumptions
Define function template which matches all other types:
void function(int); // this will be selected for int only
template <class T>
void function(T) = delete; // C++11
This is because non-template functions with direct matching are always considered first. Then the function template with direct match are considered - so never function<int> will be used. But for anything else, like char, function<char> will be used - and this gives your compilation errrors:
void function(int) {}
template <class T>
void function(T) = delete; // C++11
int main() {
function(1);
function(char(1)); // line 12
}
ERRORS:
prog.cpp: In function 'int main()':
prog.cpp:4:6: error: deleted function 'void function(T) [with T = char]'
prog.cpp:12:20: error: used here
This is C++03 way:
// because this ugly code will give you compilation error for all other types
class DeleteOverload
{
private:
DeleteOverload(void*);
};
template <class T>
void function(T a, DeleteOverload = 0);
void function(int a)
{}
You can't directly, because a char automatically gets promoted to int.
You can resort to a trick though: create a function that takes a char as parameter and don't implement it. It will compile, but you'll get a linker error:
void function(int i)
{
}
void function(char i);
//or, in C++11
void function(char i) = delete;
Calling the function with a char parameter will break the build.
See http://ideone.com/2SRdM
Terminology: non-construcing functions? Do you mean a function that is not a constructor?
8 years later (PRE-C++20, see edit):
The most modern solution, if you don't mind template functions -which you may mind-, is to use a templated function with std::enable_if and std::is_same.
Namely:
// Where we want to only take int
template <class T, std::enable_if_t<std::is_same_v<T,int>,bool> = false>
void func(T x) {
}
EDIT (c++20)
I've recently switched to c++20 and I believe that there is a better way. If your team or you don't use c++20, or are not familiar with the new concepts library, do not use this. This is much nicer and the intended method as outlines in the new c++20 standard, and by the writers of the new feature (read a papers written by Bjarne Stroustrup here.
template <class T>
requires std::same_as(T,int)
void func(T x) {
//...
}
Small Edit (different pattern for concepts)
The following is a much better way, because it explains your reason, to have an explicit int. If you are doing this frequently, and would like a good pattern, I would do the following:
template <class T>
concept explicit_int = std::same_as<T,int>;
template <explicit_int T>
void func(T x) {
}
Small edit 2 (the last I promise)
Also a way to accomplish this possibility:
template <class T>
concept explicit_int = std::same_as<T,int>;
void func(explicit_int auto x) {
}
Here's a general solution that causes an error at compile time if function is called with anything but an int
template <typename T>
struct is_int { static const bool value = false; };
template <>
struct is_int<int> { static const bool value = true; };
template <typename T>
void function(T i) {
static_assert(is_int<T>::value, "argument is not int");
return;
}
int main() {
int i = 5;
char c = 'a';
function(i);
//function(c);
return 0;
}
It works by allowing any type for the argument to function but using is_int as a type-level predicate. The generic implementation of is_int has a false value but the explicit specialization for the int type has value true so that the static assert guarantees that the argument has exactly type int otherwise there is a compile error.
Maybe you can use a struct to make the second function private:
#include <cstdlib>
struct NoCast {
static void function(int i);
private:
static void function(char c);
};
int main(){
int i(5);
NoCast::function(i); //<- this is acceptable
char c('a');
NoCast::function(c); //<- Error
return EXIT_SUCCESS;
}
void NoCast::function(int i){return;}
This won't compile:
prog.cpp: In function ‘int main()’:
prog.cpp:7: error: ‘static void NoCast::function(char)’ is private
prog.cpp:16: error: within this context
For C++14 (and I believe C++11), you can disable copy constructors by overloading rvalue-references as well:
Example:
Say you have a base Binding<C> class, where C is either the base Constraint class, or an inherited class. Say you are storing Binding<C> by value in a vector, and you pass a reference to the binding and you wish to ensure that you do not cause an implicit copy.
You may do so by deleting func(Binding<C>&& x) (per PiotrNycz's example) for rvalue-reference specific cases.
Snippet:
template<typename T>
void overload_info(const T& x) {
cout << "overload: " << "const " << name_trait<T>::name() << "&" << endl;
}
template<typename T>
void overload_info(T&& x) {
cout << "overload: " << name_trait<T>::name() << "&&" << endl;
}
template<typename T>
void disable_implicit_copy(T&& x) = delete;
template<typename T>
void disable_implicit_copy(const T& x) {
cout << "[valid] ";
overload_info<T>(x);
}
...
int main() {
Constraint c;
LinearConstraint lc(1);
Binding<Constraint> bc(&c, {});
Binding<LinearConstraint> blc(&lc, {});
CALL(overload_info<Binding<Constraint>>(bc));
CALL(overload_info<Binding<LinearConstraint>>(blc));
CALL(overload_info<Binding<Constraint>>(blc));
CALL(disable_implicit_copy<Binding<Constraint>>(bc));
// // Causes desired error
// CALL(disable_implicit_copy<Binding<Constraint>>(blc));
}
Output:
>>> overload_info(bc)
overload: T&&
>>> overload_info<Binding<Constraint>>(bc)
overload: const Binding<Constraint>&
>>> overload_info<Binding<LinearConstraint>>(blc)
overload: const Binding<LinearConstraint>&
>>> overload_info<Binding<Constraint>>(blc)
implicit copy: Binding<LinearConstraint> -> Binding<Constraint>
overload: Binding<Constraint>&&
>>> disable_implicit_copy<Binding<Constraint>>(bc)
[valid] overload: const Binding<Constraint>&
Error (with clang-3.9 in bazel, when offending line is uncommented):
cpp_quick/prevent_implicit_conversion.cc:116:8: error: call to deleted function 'disable_implicit_copy'
CALL(disable_implicit_copy<Binding<Constraint>>(blc));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Full Source Code: prevent_implicit_conversion.cc
Well, I was going to answer this with the code below, but even though it works with Visual C++, in the sense of producing the desired compilation error, MinGW g++ 4.7.1 accepts it, and invokes the rvalue reference constructor!
I think it must be a compiler bug, but I could be wrong, so – anyone?
Anyway, here's the code, which may turn out to be a standard-compliant solution (or, it may turn out that that's a thinko on my part!):
#include <iostream>
#include <utility> // std::is_same, std::enable_if
using namespace std;
template< class Type >
struct Boxed
{
Type value;
template< class Arg >
Boxed(
Arg const& v,
typename enable_if< is_same< Type, Arg >::value, Arg >::type* = 0
)
: value( v )
{
wcout << "Generic!" << endl;
}
Boxed( Type&& v ): value( move( v ) )
{
wcout << "Rvalue!" << endl;
}
};
void function( Boxed< int > v ) {}
int main()
{
int i = 5;
function( i ); //<- this is acceptable
char c = 'a';
function( c ); //<- I would NOT like this to compile
}
I first tried PiotrNycz's approach (for C++03, which I'm forced to use for a project), then I tried to find a more general approach and came up with this ForcedType<T> template class.
template <typename T>
struct ForcedType {
ForcedType(T v): m_v(v) {}
operator T&() { return m_v; }
operator const T&() const { return m_v; }
private:
template <typename T2>
ForcedType(T2);
T m_v;
};
template <typename T>
struct ForcedType<const T&> {
ForcedType(const T& v): m_v(v) {}
operator const T&() const { return m_v; }
private:
template <typename T2>
ForcedType(const T2&);
const T& m_v;
};
template <typename T>
struct ForcedType<T&> {
ForcedType(T& v): m_v(v) {}
operator T&() { return m_v; }
operator const T&() const { return m_v; }
private:
template <typename T2>
ForcedType(T2&);
T& m_v;
};
If I'm not mistaken, those three specializations should cover all common use cases. I'm not sure if a specialization for rvalue-reference (on C++11 onwards) is actually needed or the by-value one suffices.
One would use it like this, in case of a function with 3 parameters whose 3rd parameter doesn't allow implicit conversions:
function(ParamType1 param1, ParamType2 param2, ForcedType<ParamType3> param3);

passing this as template argument

I have two classes test1 and test2:
struct test1
{
int r;
test1() {}
test1(int value) : r(value) {}
test1 foo() const;
};
struct test2
{
int r;
test2() {}
test2(int value) : r(value) {}
};
template <typename t>
struct data_t
{
static const t one;
};
template <> const test1 data_t<test1>::one = test1(1);
template <> const test2 data_t<test2>::one = test2(1);
then i created a function to do somthing:
template <typename t, const t& value>
t do_somthing()
{ return value; };
the action of do_something is straightforward, it returns a copy of value, so in main function:
int main()
{
test1 r = do_somthing<test1, data_t<test1>::one>();
}
the problem happens when implementing test1::foo
test1 test1::foo() const
{ return do_somthing<test1, *this>(); }
the compiler stops with error:
'this' : can only be referenced inside non-static member functions
with *this it becomes test1 const& which acceptable as 2nd parameter, so why this error?
When you call a template method with explicit mention of parameters like,
do_somthing<test1, data_t<test1>::one>(); //(1) ok
do_somthing<test1, *this>(); // (2) error
then compiler expects that the explicit arguments should be compile time constants. In your (2)nd case, *this is not resolvable to a compile time constant, so you are getting the compiler error.
Change the definition to below:
template <typename t>
t do_somthing(const t& value)
{ return value; };
and now when you call as,
do_somthing<test1>(*this); // (2) ok
it should work. Because, now const t& doesn't need to be a compile time constant, even though it's resolved at compile time.
The compiler tells you exactly why this won't work, 'this' : can only be referenced inside non-static member functions. It's not usable in any other context.
If you want to templatize this function in this manner you have to use a template function that has the ability to deduce the argument type at compile time, like this:
template <class T>
T copy_value(const T& value)
{
return value;
}
class A
{
public:
A clone()
{
return copy_value(*this);
}
};
int main()
{
int x = 999;
int y = copy_value(x);
double d = 9.99;
double e = copy_value(d);
std::string s = "Test";
std::string t = copy_value(s);
return 0;
}
In each of the above examples, the function template is deduced at compile time so the compiler can properly generate the code necessary. Your classes that you use with this template should be appropriately copyable, and copy-constructable.

Template instantiation with VARIANT return type

An explicit instantiation of a static template member function keeps failing to compile with the message error C2785: 'at_Intermediate CUtil::convert_variant(const VARIANT &)' and '<Unknown>' have different return types
When I make a corresponding class with non-static member functions, the compiler likes me.
// utility class - static methods
struct CUtil {
template< typename at_Intermediate > static at_Intermediate convert_variant( const VARIANT &v ) ;
template<> static VARIANT convert_variant<VARIANT >( const VARIANT &v ) { return v; } //
template<> static double convert_variant<double >( const VARIANT &v ) { return v.dblVal; }
template<> static long convert_variant<long >( const VARIANT &v ) { return v.lVal ; }
template<> static BSTR convert_variant<BSTR >( const VARIANT &v ) { return v.bstrVal; }
};
This is a composed question:
Why does the compiler complain about a function "Unknown" while it's clearly known?
What triggers this message - it disappears when the function is made global or non-static.
EDIT:
after some useful hints from Josh: is it not allowed to explicitly instantiate template functions within the class declaration?
Apparently you may only use explicit template specialization at namespace scope although I can't find this in the standard (but GCC says as much). The following works for me (on GCC):
struct CUtil {
template< typename at_Intermediate > static at_Intermediate convert_variant( const VARIANT &v ) ;
};
template<> VARIANT CUtil::convert_variant<VARIANT >( const VARIANT &v ) { return v; }
template<> double CUtil::convert_variant<double >( const VARIANT &v ) { return v.dblVal; }
template<> long CUtil::convert_variant<long >( const VARIANT &v ) { return v.lVal ; }
template<> BSTR CUtil::convert_variant<BSTR >( const VARIANT &v ) { return v.bstrVal; }
EDIT It is in the standard:
14.7.2.5:
An explicit instantiation of a class or function template specialization is placed in the namespace in which the template is defined. An explicit instantiation for a member of a class template is placed in the namespace where the enclosing class is defined. An explicit instantiation for a member template is placed in the namespace where the enclosing class or class template is defined.
(All emphasis added by me.)
Try it this way:
struct CUtil {
template< typename T >
static T convert_variant(const VARIANT &);
};
template<> int CUtil::convert_variant<int>(const VARIANT &);
template<> VARIANT CUtil::convert_variant<VARIANT>(const VARIANT &);
You can't explicitly specialize a template inside a class scope. See here.
The wierd issue with VS2008 is that this does work.
struct CUtil {
template< typename T >
static T convert_variant(const VARIANT &);
template<>
static int convert_variant<int>(const VARIANT &);
};
And this:
struct CUtil {
template< typename T > static void convert_variant(T);
template<> static void convert_variant<VARIANT >(VARIANT);
};