1

In the below code:

template <typename T>
struct templatedStruct
{

};

template <typename T>
void func(T arg)
{
    // How to find out if T is type templatedStruct of any type, ie., templatedStruct<int> or
    // templatedStruct<char> etc?
}

int main()
{
    templatedStruct<int> obj;
    func(obj);
}

Is the only way to inherit templatedStruct from something else?

  struct Base {};

template <typename T>
struct templatedStruct : Base
{

};

template <typename T>
void func(T arg)
{
    std::is_base_of_v< Base, T>;
    std::derived_from<T, Base>; // From C++ 20
}
vvv444
  • 2,764
  • 1
  • 14
  • 25
Zebrafish
  • 11,682
  • 3
  • 43
  • 119
  • 1
    Does this answer your question? [How to tell if template type is an instance of a template class?](https://stackoverflow.com/questions/44012938/how-to-tell-if-template-type-is-an-instance-of-a-template-class) – Brian61354270 Apr 06 '21 at 02:56

2 Answers2

6

You can define a type trait for it.

template <typename T>
struct is_templatedStruct : std::false_type {};
template <typename T>
struct is_templatedStruct<templatedStruct<T>> : std::true_type {};

then

template <typename T>
void func(T arg)
{
    // is_templatedStruct<T>::value would be true if T is an instantiation of templatedStruct
    // otherwise false
}

LIVE

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
2

You could write an overload set that returns that handles the cases differently, and returns a boolean accordingly:

template <typename T>
constexpr bool check(T const &) { return false; }

template <typename T>
constexpr bool check(templatedStruct<T> const &) { return true; }

And then use it like this:

template <typename T>
void func(T arg)
{
    if(check(arg)) // this could be 'if constexpr' if you want only
                   // one branch to be compiled
        // ...
}
cigien
  • 57,834
  • 11
  • 73
  • 112
  • You can get a lot of mileage from a pair of such overloads. If written with care, they can be part of constant evaluation (and that `if` can be an `if constexpr`). https://wandbox.org/permlink/BBG9WA53N64s53fA – StoryTeller - Unslander Monica Apr 06 '21 at 07:08
  • @StoryTeller-UnslanderMonica Yes, that's definitely an improvement, thanks. I've edited the answer to do that. – cigien Apr 06 '21 at 07:19