How to static_assert in member templates only when they are actually used?
Consider this simple class:
template<class T>
class Foo{
public:
Foo(T const& val)
: _val(val) {}
template<class U>
Foo(Foo<U> const&){
static_assert(false,"Cannot convert from Foo<U> to Foo<T>.");
}
operator T&() { return _val; }
operator T const&() const{ return _val; }
private:
T _val;
};
It allows implicit construction from the template type and implicit conversion back to that type, a simple wrapper.
Now, I do not want to enable conversion between unrelated Foo
s, which would be possible because of these implicit constructions / conversions. I could make the templated copy-ctor private, but I wan't to emit a helpful diag开发者_如何学运维nostic through static_assert
.
The problem, as shown here on Ideone is that the static_assert
failes even when I not even try to copy the type! In Visual Studio, I get the behaviour I want, though I think that is due to the way VS parses templates. Is there any way to get this working?
It fails compilation, because compiler can clearly seestatic_assert
would fail no matter what. It doesn't depend onU
and T
in any way.
I think you wanted something like this:
static_assert(std::is_same<T,U>::value,"Cannot convert from Foo<U> to Foo<T>.");
It seems std::is_convertible is the solution.
From http://en.cppreference.com/w/cpp/types/is_convertible :
"If an imaginary rvalue of type From can used in the return statement of a function returning To, that is, if it can be converted to To using implicit conversion, provides the member constant value equal to true. Otherwise value is false. "
精彩评论