繁体   English   中英

C ++模板专用吸气剂

[英]C++ template specialized getters

我目前正在编写一个使用NURBS surfaces的程序,您可以在两个方向( UV )上执行算法。 为了避免代码重复,我尝试使用模板,但是我绝不使用模板。 这是我想做的一个小例子:

#include <iostream>

enum class Dir {
    U, V
};

struct Foo {

    unsigned cu, cv;

    Foo(unsigned cu, unsigned cv) : cu(cu), cv(cv) {};

    template<Dir>
    const Dir otherDir();

    template<>
    const Dir otherDir<Dir::V>() {
        return Dir::U;
    }

    template<>
    const Dir otherDir<Dir::U>() {
        return Dir::V;
    }

    template<Dir>
    unsigned count();

    template<>
    unsigned count<Dir::U>() {
        return cu;
    }

    template<>
    unsigned count<Dir::V>() {
        return cv;
    }

    template<Dir d>
    unsigned totalCount() {
        auto c = count<d>();
        auto cOther = count<otherDir<d>()>();
        return c * cOther;
    }

};

int main() {
    Foo f(3,2);
    std::cout << (f.count<Dir::U>() == 3) << std::endl;
    std::cout << (f.otherDir<Dir::U>() == Dir::V) << std::endl;
    std::cout << f.totalCount<Dir::U>() << std::endl;
}

但这由于main中的最后一行而无法编译(VS2015,但我认为这不是编译器的错):

1>...\main.cpp(42): error C2672: 'Foo::count': no matching overloaded function found
1>...\main.cpp(52): note: see reference to function template instantiation 'unsigned int Foo::totalCount<Dir::U>(void)' being compiled
1>...\main.cpp(42): error C2975: 'unnamed-parameter': invalid template argument for 'Foo::count', expected compile-time constant expression
1>...\main.cpp(27): note: see declaration of 'unnamed-parameter'
1>...\main.cpp(43): error C3536: 'cOther': cannot be used before it is initialized

我接近上述功能的唯一方法是同时指定主方向和另一个方向作为模板参数,如下所示:

struct Foo {

    ...

    template<Dir d, Dir otherD>
    unsigned totalCount() {
        auto c = count<d>();
        auto cOther = count<otherD>();
        return c * cOther;
    }

};

int main() {
    Foo f(3,2);
    std::cout << f.totalCount<Dir::U, Dir::V>() << std::endl;
}

但这似乎不是很优雅。

问题可能在这里:

auto cOther = count<otherDir<d>()>();

模板在编译时被“解析”。 您应该将constexpr用于otherDir<d>()因为仅是简单的const并不意味着该方法可以在编译时求值。

更传统的方法是使用otherDir结构代替方法。 创建结构模板,两个实例将具有static const value = VU

或者您可以用空结构替换枚举。

或者,更好的是,您可以尝试不使用模板来实现它,并为维创建类,并且每个维都有一个对象。

otherDir<d>()不是constexpr ,不能在模板参数( count<otherDir<d>()>() )中使用。

您可以向该方法添加constexpr (和static ),或使用旧的struct来处理该问题:

template <Dir> struct otherDir;

template<>
struct otherDir<Dir::U>
{
    static constexpr Dir value = Dir::V;
};

template<>
struct otherDir<Dir::V>
{
    static constexpr Dir value = Dir::U;
};

演示版

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM