【发布时间】:2014-07-29 16:46:01
【问题描述】:
假设我有一对相关的模板,我想自动将参数转换为某个函数,从其中一个到另一个。我怎样才能做到这一点?
template<int a> struct bar;
template<int a, int b> struct foo {
operator bar<a> const (); // operator-based conversion
};
template<int a> struct bar : public foo<a, a> {
bar() { }
template<int b> bar(const foo<a, b>&) { } // constructor-based conversion
};
template<int a, int b> foo<a, b>::operator bar<a> const () { return bar<a>(); }
template<int a> void f(bar<a> x, bar<a> y) { }
int main() {
bar<1> x;
foo<1, 2> y;
f(x, y);
}
对此,gcc 4.8.3 说:
template argument deduction/substitution failed: ‘foo<1, 2>’ is not derived from ‘bar<a>’
目的是通过我控制的一些代码将f 的第二个参数从foo<1,2> 转换为bar<1>。但显然,模板化转换构造函数和非模板化转换运算符都不适用于这种情况。有什么成语可以用来完成这项工作吗?
【问题讨论】:
-
我认为这是因为
void f()是一个模板函数;隐式参数转换对于模板函数是非法的。试试void f(bar<1> x, bar<1> y)
标签: c++ templates c++11 type-conversion