Home > Net >  Get object type without template parameters
Get object type without template parameters

Time:07-16

I need to be able to have any object that takes a single bool as a template parameter, and obtain the type of that object without the bool, so I can then create a similarly typed object but of a different bool.

This is what I came up with, but it does not compile. How can I achieve this aim please?

template<template<bool> typename ClassName, bool TheBool>
struct FT
{
  using TYPE = ClassName;
};

template<bool X>
struct T {};

int main() {

  T<true> t;
  // Somehow get the type T (without the true) so I can then create a T<false> if I want...
  using RawType = FT<decltype(t)>::TYPE;
  RawType<false> f;
}

(I have searched beforehand but came up blanks, hence this question.)

CodePudding user response:

How about this:

#include <type_traits>

template<typename T, bool TheBool> struct FT;

template<template<bool> typename ClassName, bool origBool, bool TheBool>
struct FT< ClassName<origBool>, TheBool> {

    typedef ClassName<TheBool> TYPE;
};

template<typename T, bool TheBool>
using FT_t=typename FT<T, TheBool>::TYPE;

template<bool X>
struct T {};

int main() {

  T<true> t;

  FT_t<decltype(t), false> f;

  static_assert(std::is_same_v<decltype(f), T<false>>);
}

Perhaps some of your fruitless searches were due to imprecise terminology. "any object that takes a single bool as a template parameter" is not a meaningful C term. Objects don't have "template parameters". Templates have templates parameters. Furthermore, objects, types, and templates have specific meaninges. A template is not a type, a type is not a template. "a similarly typed object but of a different bool" also is not correct terminology, either.

CodePudding user response:

A little ugly, but this works:

template<bool NewBool, template<bool> typename ClassName, bool TheBool>
ClassName<NewBool> FT(const ClassName<TheBool>&);

template<bool X>
struct T {};

int main() {
    T<true> t;
    decltype(FT<false>(t)) f;
}

Online Demo

  • Related