问题
I'm still trying to fully understand templates. I see them as special types.
Recently I was reading about template template parameters of classes and I'm wondering if it it is possible to have a template template parameter of function or variable and not only of class? Something like this:
template<typename T> void func(T); //template of function 'func'
template<int a> double var = a; //template of variable 'var'
template<template<typename> void templ_param() = func, //parameter template of function
template<int> double templ_param_0 = var //parameter template of variable
> void func1();
EDIT: If not why and what is the alternative?
回答1:
I'm wondering if it it is possible to have a template template parameter of function
No, you cannot. Your example code snippet won't work.
template <template <typename T>> void templ_param() = func,
A template template parameter must be a class template or an alias template.
From the C++ standard:
14.3.3 Template template arugments
1 A template-argument for a template template-parameter shall be the name of a class template or an alias template, expressed as id-expression.
回答2:
No, template template parameters may be only types.
[temp.param]/1 describes template parameter syntax as follows:
template-parameter:
- type-parameter
- parameter-declaration
type-parameter:
- type-parameter-key
...
opt identifieropt- type-parameter-key identifieropt
=
type-idtemplate <
template-parameter-list>
type-parameter-key...
opt identifieropttemplate <
template-parameter-list>
type-parameter-key identifieropt=
id-expressiontype-parameter-key:
class
typename
So template template parameters are put into category of type-parameters, and indeed, their declaration must contain either class
or typename
after template<...>
As an alternative you can wrap template functions and variables into classes:
template <typename T>
struct FuncWrapper {
static void func(T t) {
std::cout << "in func " << t << std::endl;
}
};
template <int a>
struct VarWrapper {
static constexpr double var = a;
};
template<
template <typename T> class FW = FuncWrapper,
template <int> class VW = VarWrapper>
void func1() {
FW<int>::func(VW<42>::var);
}
int main() {
func1<>();
}
来源:https://stackoverflow.com/questions/29219576/c-can-a-template-template-parameter-be-of-a-variable-or-function