按参数而不是按类型进行模板特化

Template specialization by argument instead by type

是否可以通过参数而不是类型来专门化模板class?

目标是拥有舒适的界面和尽可能短的执行时间。 目前我知道三种不同好处的选择。

  1. 一个 Class 根据 CTor 参数具有不同的行为
  2. 定义不同classes
  3. 专用模板 classes

第一种可能不符合执行时间要求。

第二种可能性没有很好的界面,因为每个人都必须知道有多个 classes,它们的行为略有不同。

我最喜欢第三种解决方案,但因此需要将类型声明为开关。

所以我正在寻找 1. 和 3. 之间的混合物

我可能缺少用于搜索的正确关键字。

这里是我目前知道的可能性:

#include <iostream>

/**
 * opt1 -- switch at runtime
 */
class inoutslow
{
public:
    inoutslow(bool b): _switch(b)
    {
        if(_switch)
            std::cout << "slowIn1" << std::endl;
        else
            std::cout << "slowIn2" << std::endl;
    }
    ~inoutslow()
    {
        if(_switch)
            std::cout << "slowOut1" << std::endl;
        else
            std::cout << "slowOut2" << std::endl;
    }
private:
    bool _switch;
};


/**
 * opt2 -- different self defined classes
 */
class inout1
{
public:
    inout1(){std::cout << "in1" << std::endl;}
    ~inout1(){std::cout << "out1" << std::endl;}
};

class inout2
{
public:
    inout2(){std::cout << "in2" << std::endl;}
    ~inout2(){std::cout << "out2" << std::endl;}
};


/**
 * opt3 -- specialized template 
 */
struct trueType;
struct falseType;

template<typename T>
class inout
{
public:
    inout(){std::cout << "DefaultTin" << std::endl;}
    ~inout(){std::cout << "DefaultTout" << std::endl;}
};
template  <>
class inout<trueType>
{
public:
    inout(){std::cout << "Tin1" << std::endl;}
    ~inout(){std::cout << "Tout1" << std::endl;}
};
template  <>
class inout<falseType>
{
public:
    inout(){std::cout << "Tin2" << std::endl;}
    ~inout(){std::cout << "Tout2" << std::endl;}
};

int main()
{
    inoutslow i(true);
    inoutslow j(false);
    inout1 ii;
    inout2 jj;
    inout<trueType> iii;
    inout<falseType> jjj;
}

the above code in coliru

谢谢你们——感谢所有可能发现这个问题而不是 Using template instead of switch

的人
/**
 * opt 4
 */
template<bool _switch>
class inoutT;
template  <>
class inoutT<true>
{
public:
    inoutT(){std::cout << "TTin1" << std::endl;}
    ~inoutT(){std::cout << "TTout1" << std::endl;}
};
template  <>
class inoutT<false>
{
public:
    inoutT(){std::cout << "TTin2" << std::endl;}
    ~inoutT(){std::cout << "TTout2" << std::endl;}
};

working sample of all (listed) possibilities