c++templateslambdac++14variable-templates

Is it possible to pass variable template to function through lambda?


As I know how to pass template function as template argument, I'm now struggling to pass variable template in a similar manner.

Here is minimal example of what I tried:

#define PASS_VARIABLE_TEMPLATE(name) [dummy=nullptr](auto&&...args) \
                                                    {return name<decltype(args)...>;}

//testing
template <typename T>
bool value = std::is_fundamental<T>::value;

template <typename Hax>
void print_bool(Hax h)
{
    std::cout << h(int{}) << std::endl; // no error, wrong output
    //std::cout << h(int{}, float{}) << std::endl; // error, good
}

int main()
{
    print_bool(PASS_VARIABLE_TEMPLATE(value)); //prints 0 instead of 1
}

Demo

If it compiles, then why the output is wrong?


Solution

  • template<class T>struct tag_t{using type=T; constexpr tag_t(){}};
    template<class Tag>using tagged_type=typename Tag::type;
    template<class T>constexpr tag_t<T> tag{};
    

    These help pass types as values and unpack them.

    #define PASS_VARIABLE_TEMPLATE(name) [](auto...args) \
                                                    {return name<tagged_type<decltype(args)>...>;}
    

    Inside print_bool you do:

    std::cout << h(tag<int>) << std::endl;
    

    Not sure why you do the dummy=nullptr thing.

    tag as a template can carry types unmolested.