使用虚拟参数来帮助模板专用化



我正在编写一些东西,最终我不得不使用虚拟参数来实现模板专用化,因为您无法重载返回类型。我想知道这是否正确,即其他人已经做到了,或者是否有更好的方法可以做到这一点。

namespace ObjectDetail
{
template <typename T>
inline T get(Object&, int, T&);
template <>
inline std::string get(void* handle, int index, std::string& unused) // dummy argument.
{
    return somelib_get_string(handle, index);
}
template <>
inline int get(void* handle, int index, int& unused) // dummy argument.
{
    return somelib_get_int(handle, index);
}
} // namespace ObjectDetail
class Object
{
public:
    std::string getString(int index) const
    {
        std::string unused;   // dummy variable.
        return ObjectDetail::get(m_handle, index, unused);
    }
    int getInt(int index) const
    {
        int unused;  // dummy variable.
        return ObjectDetail::get(m_handle, index, unused);
    }
private:
    void* m_handle;
}

我也希望编译器(gcc 4.6.3)足够聪明,可以弄清楚虚拟参数实际上并没有被使用。

很好。我宁愿使用几个虚拟标签类型:

class classA {};
class classB {};
class classC {};

并使用它们代替整数、字符串等。

然后做

return ObjectDetail::get(m_handle, index, classC());

您还可以将这些标记类型放在命名空间中,并更合乎逻辑地命名它们。

最新更新