Trait (计算机 科学 )
此條 |
Trait
合 并不相 交的traits(symmetric sum)产生一 个新的 trait覆 盖(asymmetric sum):对一个已有 的 trait增加 方法 ,可 以覆盖已有 的 方法 - 别名(alias): 对已
有 方法 增加 别名,从而产生一 个新的 trait 排除 (exclusion):从已有 trait中 删除方法 从而产生一 个新的 trait嵌 套的trait自 动平面 化 。例 如 给定trait S = A + X, 其中 X = B + C,那 么trait T = A + B + C等 价于 S
C++编程中 的 traits[编辑]
C++语言标准
17.3.25 [defns.traits] traits class
一 个类,封 装 了 一 套对类模板 和 函数 模 板 实例化 时操纵对象 类型是 必须的 类型和 函数 [注 释:定 义在Clauses 21, 22和 27的 traits class是 字 符 traits,提供 了 string和 iostream类所需的字 符 处理支持 。]
C++标准
示 例 [编辑]
#include <iostream>
struct no_move{};//两个marker类型
struct has_move{};
struct myValueType{
public: void move(){std::cout<<"move a myValueType obj."<<std::endl;}
};
template <typename T> struct traits{
typedef no_move move_method; //对于traits模 板 类,默 认为无move方法
void move(T* p){}//默 认为无move方法
};
template <> struct traits<myValueType>{
typedef has_move move_method;//对于myValueType,traits模 板 偏 特 化 ,定 义了有 move方法
void move(myValueType* p){p->move();} //模 板 特 化 ,有 move方法
};
template <typename T> struct Container{
void move(T* p){traits<T>().move(p);};
};
int main()
{
int i=101;
int *p1=&i;
myValueType v1;
myValueType *pv=&v1;
Container<int> c1;
Container<myValueType> c2;
c1.move(p1);
c2.move(pv);
}
C#的 支持 [编辑]
从C# 8.0开始,
using System;
namespace CSharp8NewFeatures
{
interface ILogger
{
// Traditional interface methods
void Log(string message);
void LogError(Exception exception);
// Default interface method
void LogWarning(string message)
{
Console.WriteLine(message);
}
}
class Logger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
public void LogError(Exception exception)
{
Console.WriteLine(exception.ToString());
}
}
class Program
{
static void Main(string[] args)
{
ILogger logger = new Logger();
logger.LogWarning("Some warning message");
}
}
}
Haskell[编辑]
Haskell
Java[编辑]
从Java 8开始,