模板化[]或()运算符重载 - 可以不使用类型作为arg?

时间:2016-11-10 11:52:48

标签: c++ templates operator-overloading

就像你可以这样做......

template< typename T >
T GetValue( const int index ) const;

char c = GetValue< char >( 0 );

......是否可以这样做:

template< typename T >
T operator[]( const char* key ) const;

char c = GetValue< char >( "some key" );    // *** This doesn't compile ***

......或者这个:

template< typename T >
T Foo::operator()( const char* key ) const;

char c = Foo< char >( "some key" );    // *** This doesn't compile ***

由于&lt;上述两个示例无法编译char&gt; 如果没有它,我会收到“无法推断类型”的错误(我明白为什么会这样)。

我能得到的最接近的是指定一个'默认值'来摆脱“无法演绎的类型”错误,所以像这样:

template< typename T >
T operator()( const char* key, const T& defaultValue ) const;

char c = Foo( "some key", 'x' );

但是,这不是我想要的。

修改

基本上,这就是我正在做的事情:

class Collection
{
  ...

  template< typename T >
  T operator[]( const char* key ) const;

  template< typename T >
  void Add( const char* key, const T& value );

  ...
}

这就是我想用它的方式:

Collection col;
col.Add( "some key", 123 );
col.Add( "another key", 'x' );
col.Add( "and another", 1.23 );

char c = col< char >[ "another key" ];

1 个答案:

答案 0 :(得分:1)

如果我理解正确你想要达到这样的目的:

struct S {
   template< typename T >
   T operator[]( const char* key ) const {
       return key[0];
   }
   template< typename T >
   T operator()( const char *key) const {
       return key[0];
   }
};

int main() {
   S s;
   char c = s.operator[]<char>("some key");
   c = s.operator()<char>("some key");
   (void)c;
}

[live demo]

如果该语法不适合您的应用程序,您可以尝试使用标记分派:

struct S {
   template< typename T >
   T operator()(const char *key, T) const {
       return key[0];
   }
};

int main() {
   S s;
   char c = s("some key", char{});
   (void)c;
}

[live demo]

然而,这可能更难应用于operator[],因为它只能采用一个参数。