Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Foos, 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 diagnostic 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?

like image 352
Xeo Avatar asked Jan 20 '23 10:01

Xeo


1 Answers

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>.");
like image 178
Nawaz Avatar answered Jan 31 '23 04:01

Nawaz