0

Motivation: I'm trying to warn future maintainers that if they do something in the code they must make sure to do something else too

Please note that "instantiation" here means template instantiation and not object of class instantiation.

class A;
class B;

template<class T> void foo() {}
template<class T> class X {};

void f()
{
    foo<A>();   
}

void g()
{
    X<A> x; // ok
    X<B> y; // expecting static_assert here: if instantiated X with a type, 
            // foo must be instantiated with the same type too
}
cpp114
  • 1
  • Did you already try something yourself? [Here](http://en.cppreference.com/w/cpp/types) are some useful standard facilities. – πάντα ῥεῖ Mar 03 '17 at 10:21
  • Yes, I tried doing template specialization but it fails for two reasons: – cpp114 Mar 03 '17 at 10:33
  • I'm afraid you can't couple two unrelated templates using some static assertion. Can't you integrate `foo()` into the template class? E.g. as `static` member function? – πάντα ῥεῖ Mar 03 '17 at 10:35
  • Yes, I tried doing template specialization but it fails for two reasons: (1) if I try to reference the name of the template instance (like foo), that is already instantiation. (2) I should specialize something generally false to true inside the template definition, but it is in another scope `template struct is_instantiated : std::false_type {};` `template void foo() {` `template <> struct is_instantiated : std::true_type {};` `}` – cpp114 Mar 03 '17 at 10:42
  • It is not important for me that they be 1 class - 1 function template. It would be nice in any combination... yes I can wrap the function in a class if that helps, but I couldn't find a solution that way neither – cpp114 Mar 03 '17 at 10:44
  • Are you wanting a `foo();` call, for each T, inside of `f()`? As in, `f` could be named `foo_all_the_Xs`? – Caleth Mar 03 '17 at 13:43

1 Answers1

0

As for your comment:

It would be nice in any combination... yes I can wrap the function in a class if that helps, but I couldn't find a solution that way neither

I can't really see what should be left to solve with that.

If you have the function in a template class like

template<typename T>
class X {
    static void foo() {
        // Do something involving T
    }
};

it is already guaranteed that X<A> and X<A>::foo() are instantiated for the same type.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190