jjzjj

c++ - 限制模板函数,只允许某些类型

coder 2024-02-15 原文

这里说我有一个原则上可以接受所有类型的简单模板函数:

template <class Type>
std::ostream& operator<< (std::ostream& stream, const Type subject) {
stream << "whatever, derived from subject\n";
return stream; }

我只想用这个模板来计算一些类型,比如 std::vector 和 boost::array 对象。但是,每当我将 cout 用于其他类型甚至是基本类型时,例如std::cout < int(5);,将是一个编译错误,因为现在有两种可能的=""><(std::ostream, int)="" 实现,一种是在标准="" c++="">

请问,是否可以限制我的模板功能,使其只接受我指定的几种类型?这就是当我使用 cout < int(5)="">

更清楚地说,这就是我想要做的:

template <class Type>
std::ostream& operator<< (std::ostream& stream, const Type subject) {
if (Type == TypeA or TypeB or TypeC) //use this template and do these {...};
else //ignore this template, and use operator<< provided in standard c++ library.
}

最佳答案

为此编写一个真正通用的解决方案很困难。根据 std::vectorstd::array 检查任意类型 T 的问题是后者不是类,它们是类模板。更糟糕的是,std::array 是一个带有非类型模板参数的类模板,所以你甚至不能拥有一个同时包含 std::vector 的参数包> 和 std::array

您可以通过在类型中显式包装非类型参数来稍微解决这个问题,但它变得丑陋、快速。

这是我想出的一个解决方案,它默认支持任何没有非类型模板参数的类或模板类。通过添加包装类型以将非类型参数映射到类型参数,可以支持具有非类型模板参数的模板类。

namespace detail{ 
    //checks if two types are instantiations of the same class template
    template<typename T, typename U> struct same_template_as: std::false_type {};
    template<template<typename...> class X, typename... Y, typename... Z>
    struct same_template_as<X<Y...>, X<Z...>> : std::true_type {};

    //this will be used to wrap template classes with non-type args
    template <typename T>
    struct wrapImpl { using type = T; };

    //a wrapper for std::array
    template <typename T, typename N> struct ArrayWrapper;
    template <typename T, std::size_t N>
    struct ArrayWrapper<T, std::integral_constant<std::size_t, N>> {
        using type = std::array<T,N>;   
    };

    //maps std::array to the ArrayWrapper
    template <typename T, std::size_t N>
    struct wrapImpl<std::array<T,N>> {
        using type = ArrayWrapper<T,std::integral_constant<std::size_t,N>>;   
    };

    template <typename T>
    using wrap = typename wrapImpl<typename std::decay<T>::type>::type;

    //checks if a type is the same is one of the types in TList,
    //or is an instantiation of the same template as a type in TempTList
    //default case for when this is false
    template <typename T, typename TList, typename TempTList>
    struct one_of {
        using type = std::false_type;
    };

    //still types in the first list to check, but the first one doesn't match
    template <typename T, typename First, typename... Ts, typename TempTList>
    struct one_of<T, std::tuple<First, Ts...>, TempTList> {
        using type = typename one_of<T, std::tuple<Ts...>, TempTList>::type;
    };

    //type matches one in first list, return true
    template <typename T, typename... Ts, typename TempTList>
    struct one_of<T, std::tuple<T, Ts...>, TempTList> {
        using type = std::true_type;
    };

    //first list finished, check second list
    template <typename T, typename FirstTemp, typename... TempTs>
    struct one_of<T, std::tuple<>, std::tuple<FirstTemp, TempTs...>> {
        //check if T is an instantiation of the same template as first in the list
        using type = 
            typename std::conditional<same_template_as<wrap<FirstTemp>, T>::value,
              std::true_type, 
              typename one_of<T, std::tuple<>, std::tuple<TempTs...>>::type>::type;
    };
}

//top level usage
template <typename T, typename... Ts>
using one_of = typename detail::one_of<detail::wrap<T>,Ts...>::type;

struct Foo{};
struct Bar{};

template <class Type>
auto operator<< (std::ostream& stream, const Type subject)
     //is Type one of Foo or Bar, or an instantiation of std::vector or std::array
    -> typename std::enable_if<
           one_of<Type, std::tuple<Foo,Bar>, std::tuple<std::vector<int>,std::array<int,0>>
        >::value, std::ostream&>::type
{
    stream << "whatever, derived from subject\n";
    return stream; 
}

请不要使用它,它太可怕了。

Live Demo

关于c++ - 限制模板函数,只允许某些类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32267324/

有关c++ - 限制模板函数,只允许某些类型的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  3. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  4. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  5. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  6. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  7. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  8. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  9. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  10. ruby-on-rails - RSpec:避免使用允许接收的任何实例 - 2

    我正在处理旧代码的一部分。beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)endRubocop错误如下:Avoidstubbingusing'allow_any_instance_of'我读到了RuboCop::RSpec:AnyInstance我试着像下面那样改变它。由此beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)end对此:let(:sport_

随机推荐