2011-12-01 74 views
0

我想模板铸造操作员与专业化的布尔,但它不工作。模板铸造操作员和部分专业化

template<typename T> //Don't know if the fact that C is templated itself is relevant here 
class C 
{ 
... 
     template<typename U> operator U() const { return another_namespace::MyCast<U>(*this); } 
     template<> operator bool() const { return IsValid(); } 
}; 

这使我(克++ 4.6)

非命名空间范围

显式特 'C类< T>'

现在只需

operator bool() const { return IsValid(); } 

由本身就像MyCast一样工作(这是在外部名称空间中声明的朋友函数) E)。有什么方法可以让我在这里得到预期的behHoavior?

编辑:我后来发现this,看起来像相同的基本问题,但答案(这提供了一个非常复杂的解决方案)看起来专为字符串设计。另外,那里的问题变成了含糊不清,我认为这不是问题 - 我得到了一个非常不同的编译器错误消息。

+1

不就做你想做的,如果你只是使用非模板'运营商布尔()'? – sth

+0

@sth哈!看起来像。事实证明这是一个很大的程序,我还有很多其他的错误需要我去解决,但是编译器通过了包含类C的文件。没有意识到非专业化是一种选择。把你的回答作为答案,只要一切正常,你就会得到信用。 –

+0

好的,这里你去:) – sth

回答

3

可以重载转换操作符,所以只需使用operator bool()的非模板版本应该工作:

template<typename T> 
class C 
{ 
... 
     template<typename U> operator U() const { ... } 
     operator bool() const { ... } 
}; 
0

我想专门类型转换操作模板和我有同样的问题,当我确定类定义内的专业化。但是当我搬到外面时,它就像一个魅力!

实施例定义:

struct A { 
    int i; 
    A(int v) : i(v) { 
    cout << __PRETTY_FUNCTION__ << endl; 
    } 
    template <typename T> 
    operator T() { 
    cout << __PRETTY_FUNCTION__ << " - NOT IMPLEMENTED" << endl; 
    throw; 
    return 0; 
    } 

    // Compilation error 
    // error: explicit specialization in non-namespace scope ‘struct A’ 
    //template <> 
    //operator double() { 
    // cout << __PRETTY_FUNCTION__ << " - !!! IMPLEMENTED" << endl; 
    // return (double)i; 
    //} 
}; 
// But this works well!! 
template <> 
A::operator double() { 
    cout << __PRETTY_FUNCTION__ << " - !!! IMPLEMENTED" << endl; 
    return (double)i; 
} 

实施例主要:

A a(5); 
double d = a; 
long l = a; 

输出:

A::A(int) 
A::operator T() [with T = double] - !!! IMPLEMENTED 
A::operator T() [with T = long int] - NOT IMPLEMENTED 
terminate called without an active exception 

测试:克++(Debian的4.7.2-5)4.7.2没有任何额外的ARGS。

我会尝试下大年纪了G ++,以及...